//
//  ZYCTeachingAttendanceCourseEvaluationViewController.m
//  ZDSC
//
//  Created by ZDTX on 2021/7/30.
//

#import "ZYCTeachingAttendanceCourseEvaluationViewController.h"
#import "ZYCManageCourseSelectDetailCell.h"
#import "ZYCAttendanceCourseEvaluationDetailViewController.h"
#import "ZYCTeachingAttendanceEvaluationModel.h"
#import "ZYCNoDataView.h"
#import "ZYCAttendanceEvaluateHeaderView.h"
#import "ZYCAttendanceEvaluateCell.h"
static NSInteger pageSize = 10;
@interface ZYCTeachingAttendanceCourseEvaluationViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, strong) ZYCNoDataView *noDataView;
@property (nonatomic, strong) ZYCAttendanceEvaluateHeaderView *headerView;


@end

@implementation ZYCTeachingAttendanceCourseEvaluationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.view addSubview:self.tableView];
    self.tableView.tableHeaderView = self.headerView;
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self loadNewData];
}


- (void)loadNewData{
    self.pageNum = 1;
    NSDictionary *params = @{
        @"listenClassId":self.listenClassId,
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum)
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_EvalutionList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                [self.dataSource removeAllObjects];
                if ([responseObject[@"body"][@"pageInfo"] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *pageInfo = responseObject[@"body"][@"pageInfo"];
                    NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTeachingAttendanceEvaluationModel class] json:pageInfo[@"list"]];
                    self.headerView.total = responseObject[@"body"][@"total"];
                    self.headerView.avgScore = responseObject[@"body"][@"avgScore"];
                    [self.dataSource addObjectsFromArray:array];
                    [self.tableView reloadData];
                    [self reset];
                    [self.tableView.mj_header endRefreshing];
                    if (self.dataSource.count == 0) {
                        self.noDataView.hidden = NO;
                        self.tableView.hidden = YES;
                    }else{
                        self.noDataView.hidden = YES;
                        self.tableView.hidden = NO;
                    }
                }else{
                    self.noDataView.hidden = NO;
                    self.tableView.hidden = YES;
                }
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            [self.tableView.mj_header endRefreshing];
        }];
}
-(void)loadMoreData{
    self.pageNum ++;
    NSDictionary *params = @{
        @"listenClassId":self.listenClassId,
        @"pageSize":@(pageSize),
        @"pageNum":@(self.pageNum)
    };
    [MrjSVProgressHUD showWithStatus:@"加载中..."];
    [[URLManager sharedURLManager] postUrlString:Appliance_Post_EvalutionList requestService:RequestServiceWorkBench parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(id  _Nullable responseObject) {
            [MrjSVProgressHUD dismiss];
            if (SUCCESS(responseObject[@"code"])) {
                NSDictionary *pageInfo = responseObject[@"body"][@"pageInfo"];
                NSArray *array = [NSArray yy_modelArrayWithClass:[ZYCTeachingAttendanceEvaluationModel class] json:pageInfo[@"list"]];
                if (array.count == 0) {
                    [self.tableView.mj_footer endRefreshingWithNoMoreData];
                }else{
                    [self.dataSource addObjectsFromArray:array];
                    [self.tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                }
            }else{
                [MrjToast makeToast:responseObject[@"message"] makeView:self.view];
            }
        } failure:^(NSError * _Nonnull error) {
            [self.tableView.mj_footer endRefreshing];
        }];
}

- (void)reset{
    [self.tableView.mj_footer setRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [self.tableView.mj_footer resetNoMoreData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ZYCAttendanceEvaluateCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ZYCAttendanceEvaluateCell class]) forIndexPath:indexPath];
    cell.model = self.dataSource[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ZYCAttendanceCourseEvaluationDetailViewController *vc = [ZYCAttendanceCourseEvaluationDetailViewController new];
    vc.listenClassId = self.listenClassId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
     // 圆角角度
    CGFloat radius = 7.5f;
    // 设置cell 背景色为透明
    cell.backgroundColor = UIColor.clearColor;
    // 创建两个layer
    CAShapeLayer *normalLayer = [[CAShapeLayer alloc] init];
    CAShapeLayer *selectLayer = [[CAShapeLayer alloc] init];
    // 获取显示区域大小
    CGRect bounds = CGRectInset(cell.bounds, 15, 0);
    // 获取每组行数
    NSInteger rowNum = [tableView numberOfRowsInSection:indexPath.section];
    // 贝塞尔曲线
    UIBezierPath *bezierPath = nil;
    if (rowNum == 1) {
        bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(radius, radius)];
    }else{
        if (indexPath.row == 0) {
            // 每组第一行（添加左上和右上的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerTopLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(radius, radius)];
        }else if (indexPath.row == rowNum - 1){
            // 每组最后一行（添加左下和右下的圆角）
            bezierPath = [UIBezierPath bezierPathWithRoundedRect:bounds byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight cornerRadii:CGSizeMake(radius, radius)];
        }else{
            // 每组不是首位的行不设置圆角
            bezierPath = [UIBezierPath bezierPathWithRect:bounds];
        }
    }
    // 把已经绘制好的贝塞尔曲线路径赋值给图层，然后图层根据path进行图像渲染render
     normalLayer.path = bezierPath.CGPath;
     selectLayer.path = bezierPath.CGPath;

     UIView *nomarBgView = [[UIView alloc] initWithFrame:bounds];
     // 设置填充颜色
//         normalLayer.fillColor = [UIColor colorWithWhite:0.95 alpha:1.0].CGColor;
     normalLayer.fillColor = [[UIColor whiteColor] CGColor];
     // 添加图层到nomarBgView中
     [nomarBgView.layer insertSublayer:normalLayer atIndex:0];
     nomarBgView.backgroundColor = UIColor.clearColor;
//         nomarBgView.backgroundColor = UIColor.whiteColor;
     cell.backgroundView = nomarBgView;
    //此时圆角显示就完成了，但是如果没有取消cell的点击效果，还是会出现一个灰色的长方形的形状，再用上面创建的selectLayer给cell添加一个selectedBackgroundView
     UIView *selectBgView = [[UIView alloc] initWithFrame:bounds];
     selectLayer.fillColor = [[UIColor whiteColor] CGColor];
     [selectBgView.layer insertSublayer:selectLayer atIndex:0];
     selectBgView.backgroundColor = UIColor.clearColor;
     cell.selectedBackgroundView = selectBgView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10.0f;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50.0f;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [tableView deselectRowAtIndexPath:indexPath animated:NO];
//    ZYCAttendanceCourseEvaluationDetailViewController *vc = [ZYCAttendanceCourseEvaluationDetailViewController new];
//    [self.navigationController pushViewController:vc animated:YES];
//}



#pragma mark - getters
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:[ZYCAttendanceEvaluateCell class] forCellReuseIdentifier:NSStringFromClass([ZYCAttendanceEvaluateCell class])];
        _tableView.backgroundColor = HEX_RGB(kBgLightGrayColor);
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
        _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (ZYCAttendanceEvaluateHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[ZYCAttendanceEvaluateHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50.0f)];
    }
    return _headerView;
}


- (ZYCNoDataView *)noDataView {
    if (!_noDataView) {
        _noDataView = [[ZYCNoDataView alloc] initWithFrame:self.tableView.frame];
        _noDataView.hidden = YES;
        [self.view addSubview:_noDataView];
    }
    return _noDataView;
}
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSource;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
